import time

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.support.wait import WebDriverWait

if __name__ == '__main__':
    url = "https://search.jd.com/Search?keyword=%E6%8B%AF%E6%95%91%E8%80%85&enc=utf-8&wq=%E6%8B%AF%E6%95%91%E8%80%85&pvid=ecbb7a6f94294e37ada9f3a2634e76d8"

    executable_path = "../drivers/chromedriver.exe"

    service = Service(executable_path=executable_path)
    browser = webdriver.Chrome(service=service)

    browser.get(url=url)

    try:
        # WebDriverWait 包含四个参数
        # driver webdriver 的实例对象
        # timeout 必须在时间范围内进行响应，否则抛出异常
        # poll_frequency 检测的时间周期，默认 0.5s
        # ignored_exceptions 忽略的异常
        wait = WebDriverWait(driver=browser, timeout=10, poll_frequency=1)
        # 在 10s 范围内进行等待，每隔 0.5s 检测一次
        element = wait.until(expected_conditions.presence_of_element_located((By.CLASS_NAME, "pn-next")))
        element.click()
        print("切换到下一页")
    except Exception:
        print("在等待时间内未响应")
    time.sleep(10)

    browser.quit()